import 'package:cached_network_image/cached_network_image.dart';
import 'package:ceramics/util/ab_oss_fetch_util.dart';
import 'package:ceramics/util/empty.dart';
import 'package:ceramics/widgets/ab_network_image.dart';
import 'package:flutter/material.dart';

class ABImage extends StatelessWidget {
  final String? url;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final Widget? placeholder;
  const ABImage({super.key,required this.url
    ,this.width,this.height,this.fit,this.placeholder
  });

  @override
  Widget build(BuildContext context) {
    var aURL = url;
    if (url?.startsWith('http') == false) {
      if (url?.startsWith('images') == true) {
        return Image.asset(url!,width: width,height: height,fit: fit);
      }
      try {
        aURL = OssCaches.ossCaches.firstWhere((element) => element.mediaPath == url).mediaUrl;
      } catch (e) {
        if (!isNullOrEmpty(url)) {
          return ABNetworkImage(url: url!,width: width,height: height, type: ShowImageType.origin);
        }
      }
    } else if (url?.startsWith('livchat') == true) {
      return ABNetworkImage(url: url!,width: width,height: height);
    }
    return CachedNetworkImage(imageUrl: aURL ?? "",
      width: width,
      height: height,
      fit: fit,
      placeholder: (context, url) => placeholder ?? Container(
        width: width,
        height: height,
        color: Colors.grey,
      ),
      errorWidget: (context, url, error) => const Icon(Icons.error));
  }
}

class ABCircleAvatar extends StatelessWidget {
  final String? url;
  final double size;
  const ABCircleAvatar({super.key,required this.url,required this.size});

  @override
  Widget build(BuildContext context) {
    var aURL = url;
    if (url?.startsWith('http') == false) {
      try {
        aURL = OssCaches.ossCaches.firstWhere((element) => element.mediaPath == url).thumbUrl;
      } catch (e) {
        print(e);
      }
    }
    return ClipRRect(
        borderRadius: BorderRadius.circular(size/2),
        child: ABImage(url: aURL, width: size, height: size));
  }
}
